﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Client;
using SPOnlineSolutionInstaller.ClaimAuth;
using SPOnlineSolutionInstaller.Utils;
using System.IO;

namespace SPOnlineSolutionInstaller
{
    class Program
    {
        [STAThread] 
        static void Main(string[] args)
        {
            //check command line parameters
            CommandArgsManager parameters = new CommandArgsManager(args);            
            if (!System.IO.File.Exists(parameters["solution"]) || String.IsNullOrEmpty(parameters["solution"])) throw new ArgumentException("Solution file needed !");
            if (String.IsNullOrEmpty(parameters["url"])) throw new ArgumentException("SharePoint Online url needed !");

            //get the office 365 context
            using (ClientContext context = ClaimClientContext.GetAuthenticatedContext(parameters["url"]))
            {
                if (context != null)
                {
                    //get the solutions list
                    List solutionList = context.Site.GetCatalog(121);

                    //upload the solution file
                    FileCreationInformation info = new FileCreationInformation()
                    {
                        Overwrite = false,
                        Url = Path.GetFileName(parameters["solution"]),
                        Content = System.IO.File.ReadAllBytes(parameters["solution"])
                    };
                    Microsoft.SharePoint.Client.File solution = solutionList.RootFolder.Files.Add(info);
                    context.Load(solution);
                    context.ExecuteQuery();
                    Console.WriteLine("Solution loaded correctly on SharePoint Online !");
                }
            }
            Console.ReadLine();
        }
    }
}
